<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogFormVisible"
    width="500px"
    @close="close"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      :status-icon="true"
      label-width="100px"
    >
      <el-form-item
        label="管理员姓名"
        prop="name"
      >
        <el-input
          v-model.trim="form.name"
          autocomplete="off"
          placeholder="请输入管理员姓名"
          clearable
        />
      </el-form-item>
      <el-form-item
        label="管理员级别"
        prop="level"
      >
        <el-select
          v-model="form.level"
          placeholder="请选择管理员级别"
          clearable
          @change="clearMes"
        >
          <el-option
            v-for="item in levelAtt"
            :key="item.value"
            :label="item.name"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="form.level == 0"
        label="所属级别"
        prop="areaOreTownWrap"
      >
        <el-cascader
          v-model="form.areaOreTownWrap"
          :options="townCascader"
          :props="townOption"
          placeholder="请选择领导所属区或镇"
          change-on-select	
          clearable
          @change="townChange"
        />
      </el-form-item>
      <el-form-item
        v-if="form.level == 1"
        label="所属区"
        prop="area"
      >
        <el-cascader
          v-model="form.area"
          :options="areaCascader"
          placeholder="请选择管理员所属区"
          :props="areaOption"
          clearable
          @change="areaChange"
        />
      </el-form-item>
      <el-form-item
        v-if="form.level == 2"
        label="所属镇"
        prop="townWrap"
      >
        <el-cascader
          v-model="form.townWrap"
          :options="townCascader"
          :props="townOption"
          placeholder="请选择管理员所属镇"
          clearable
          @change="townChange"
        />
      </el-form-item>
      <el-form-item
        v-if="form.level == 3"
        label="所属村"
        prop="villageWrap"
      >
        <el-cascader
          v-model="form.villageWrap"
          :options="villageCascader"
          :props="villageProp"
          placeholder="请选择所属村"
          :show-all-levels="false"
          clearable
          @change="change"
        />
      </el-form-item>
      <el-form-item
        label="管理员账号"
        prop="username"
      >
        <el-input
          v-model.trim="form.username"
          autocomplete="off"
          placeholder="请输入管理员账号"
          clearable
        />
      </el-form-item>
      <el-form-item
        label="管理员密码"
        prop="password"
      >
        <el-input
          v-model="form.password"
          type="password"
          auto-complete="off"
          :placeholder="id ? '不填则默认原来密码': '请填写密码'"
        />
      </el-form-item>
      <el-form-item
        label="确认密码"
        prop="checkPass"
      >
        <el-input
          v-model="form.checkPass"
          type="password"
          auto-complete="off"
          :placeholder="id ? '不填则默认原来密码': '请填写密码'"
        />
      </el-form-item>
    </el-form>
    <div
      slot="footer"
      class="dialog-footer"
    >
      <el-button @click="close">
        取 消
      </el-button>
      <el-button
        type="primary"
        @click="save"
      >
        确 定
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
//手动添加
import { mapGetters } from "vuex";
export default {
  name: "TableEdit",
  props: ["fetchData"],
  computed: {
    ...mapGetters({
      user: "user/info",
    }),
  },
  data() {
    var validatePass = (rule, value, callback) => {
      console.log(value)
      if(this.id && !value) {
        callback();
      } 
      if (value === '' || !value) {
        callback(new Error('请输入密码'));
      } else {
        if (this.form.checkPass !== '') {
          this.$refs.form.validateField('checkPass');
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if(this.id && !value) {
        callback();
      } 
      if (value === '' || !value) {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.form.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    }
    return {
      form: {
        name: "",
        username: "",
        area: "",
        townWrap: "",
        townWrap: "",
        town: "",
        village: "",
        villageWrap: [],
        level: "",
        password: "",
        checkPass: "",
      },
      id: null,
      created: true,
      rules: {
        name: [{ required: true, trigger: "blur", message: "请输入管理员用户名称" }],
        username: [{ required: true, trigger: "blur", message: "请输入管理员账户" }],
        level: [{ required: true, trigger: "change", message: "请选择管理员级别" }],
        townWrap: [{ required: true, trigger: "change", message: "请选择所属镇" }],
        town: [{ required: true, trigger: "change", message: "请选择所属镇" }],
        area: [{ required: true, trigger: "change", message: "请选择所属区" }],
        villageWrap: [{ required: true, trigger: "change", message: "请选择所属村" }],
        password: [{  validator: validatePass, trigger: 'blur' }],
        checkPass: [{  validator: validatePass2, trigger: 'blur' }],
        areaOreTownWrap: [{ required: true, trigger: "change", message: "请选择所属区或镇" }],
      },
      levelAtt: [
        {
          name: "领导",
          value: 0
        },
        {
          name: "区级管理员",
          value: 1
        },
        {
          name: "镇级管理员",
          value: 2
        },
        {
          name: "村级管理员",
          value: 3
        }
      ],
      title: "",
      dialogFormVisible: false,
      areaCascader: [],
      townCascader: [],
      villageCascader: [],
      areaOption: {
        label: "name",
        value: "id",
      },
      townOption: {
        label: "name",
        value: "id",
        children: "town"
      },
      villageProp: {
        label: "name",
        value: "id",
      },
    };
  },
  created() {
    this.setLevelAtt()
    this.init()
  },
  methods: {
    async showEdit(row) {

      if (!row) {
        this.title = "添加";
        this.created = true;
      } else {
        this.id = row.id;
        const res = await this.$http.get(`user/${this.id}?join=area&join=town&join=village`);

        if(res.data.level == 3) {
          res.data.villageWrap = [res.data.area.id, res.data.town.id, res.data.village.id];
          this.change(res.data.villageWrap)
        } 

        if(res.data.level == 1) {
          res.data.area = [res.data.area.id];
          this.form = Object.assign({}, res.data);
          this.areaChange(res.data.area)
        }

        if(res.data.level == 0) {
          res.data.areaOreTownWrap = res.data.town ?  [res.data.area.id, res.data.town.id] : [res.data.area.id] 
          console.log(res.data.areaOreTownWrap)
          this.townChange(res.data.areaOreTownWrap)
        }

        if(res.data.level == 2) {
          res.data.townWrap = [res.data.area.id, res.data.town.id];
          this.townChange(res.data.townWrap)
        } 
        
        this.form = Object.assign({}, res.data);
        this.title = "编辑";
        this.created = false;
      }
      this.dialogFormVisible = true;
    },
    close() {
      this.$refs["form"].resetFields();
      this.form = this.$options.data().form;
      this.dialogFormVisible = false;
      this.id = null
    },
    save() {
      
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.resPip()
          if (this.created) {
            this.create();
          } else {
            this.edit();
          }
        } else {
          return false;
        }
      });
    },
    async create() {
      const res = await this.$http.post(`user`, this.createForm);
      if (res.status == 201) {
        this.$baseMessage("新增成功", "success");
        this.$emit("fetchData");
        this.$refs["form"].resetFields();
        this.dialogFormVisible = false;
        this.form = this.$options.data().form;
      } else {
        this.$baseMessage("新增失败", "error");
      }
    },
    async edit() {
      const res = await this.$http.put(`user/${this.id}`, this.createForm);
      if (res.status == 200) {
        this.$baseMessage("修改成功", "success");
        this.$emit("fetchData");
        this.$refs["form"].resetFields();
        this.dialogFormVisible = false;
        this.form = this.$options.data().form;
      } else {
        this.$baseMessage("修改失败", "error");
      }
    },
    resPip() {
      this.createForm = JSON.parse(JSON.stringify(this.form));
      if(this.createForm.level == 0) {
        this.createForm.village = null
      } else if(this.createForm.level == 1) {
        this.createForm.village = null
        this.createForm.town = null
      } else if (this.createForm.level == 2) {
        this.createForm.village = null
      }
      delete this.createForm.checkPass
    },
    async init() {
      const res = await this.$http.get(`area?join=town&join=town.village`);
      this.areaCascader = JSON.parse(JSON.stringify(res.data)) 
      this.townCascader = JSON.parse(JSON.stringify(res.data))
      console.log(this.townCascader)
      res.data.forEach(area => {
        area.value = area.id;
        area.label = area.name;
        area.children = area.town;
        if (area.town.length > 0) {
          area.town.forEach(town => {
            town.value = town.id;
            town.label = town.name;
            town.children = town.village;
          });
          this.villageCascader = res.data;
          this.setSelectItem()
        }
      });
    },
    async change(val) {
      this.form.area = val[0]
      this.form.town = val[1]
      this.form.village = val[val.length - 1];
    },
    clearMes() {
      this.form.area = ""
      this.form.townWrap = []
      this.form.town = ""
      this.form.villageWrap = []
      this.form.village = ""
    },
    async areaChange(val) {
      this.form.area = val[0];
    },
    async townChange(val) {
      this.form.town = val[1];
      this.form.area = val[0];
    },
    setLevelAtt() {
      if(this.user.level == -2) {
        //超级管理员
         this.levelAtt = [
                          {
                            name: "系统管理员",
                            value: -1
                          },
                          {
                            name: "领导",
                            value: 0
                          },
                          {
                            name: "区级管理员",
                            value: 1
                          },
                          {
                            name: "镇级管理员",
                            value: 2
                          },
                          {
                            name: "村级管理员",
                            value: 3
                          }
                        ]
      } else if(this.user.level == -1) {
        //系统管理员
         this.levelAtt = [
                          {
                            name: "领导",
                            value: 0
                          },
                          {
                            name: "区级管理员",
                            value: 1
                          },
                          {
                            name: "镇级管理员",
                            value: 2
                          },
                          {
                            name: "村级管理员",
                            value: 3
                          }
                        ]
      } else if(this.user.level == 0) {
        //领导
        this.levelAtt = [
                          {
                            name: "区级管理员",
                            value: 1
                          },
                          {
                            name: "镇级管理员",
                            value: 2
                          },
                          {
                            name: "村级管理员",
                            value: 3
                          }
                        ]
      } else if(this.user.level == 1) {
        //区
        this.levelAtt = [
                          {
                            name: "镇级管理员",
                            value: 2
                          },
                          {
                            name: "村级管理员",
                            value: 3
                          }
                        ]
      } else if (this.user.level == 2) {
        // 镇
        this.levelAtt = [
                          {
                            name: "村级管理员",
                            value: 3
                          }
                        ]
      } 
    },
    setSelectItem() {
      if(this.user.level < 1) {
      } else if (this.user.level == 1) {
        //区级
        this.villageCascader.forEach((area) => {
          if(area.id == this.user.area.id) {
            area.disabled = false
          } else {
            area.disabled = true
            if (area.town.length > 0) {
              area.town.forEach((town) => {
                town.disabled = true
              });
            }
          }
        });
      } else if (this.user.level == 2) {
        //镇级
        this.villageCascader.forEach((area) => {
          if(area.id == this.user.area.id) {
            area.disabled = false
             if (area.town.length > 0) {
              area.town.forEach((town) => {
                if(town.id == this.user.town.id) {
                  town.disabled = false
                } else {
                  town.disabled = true
                }
              });
            }
          } else {
            area.disabled = true
            if (area.town.length > 0) {
              area.town.forEach((town) => {
                  town.disabled = true
              });
            }
          }
        });
      } 
        else if (this.user.level == 3) {
          //村级
        this.change([this.user.village.id])
      } 
    },
  },
};
</script>
